<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef } from "vue";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IDomEditor } from '@wangeditor/editor'
import { getStorage } from '@/composables/storage'



defineOptions({
  name: "picUpload"
});

const props = defineProps({
  htmlVal: {
    type: String,
    default: ''
  },
})
const emit = defineEmits(["updatelVal"])

const token = getStorage('token')


const mode = "default";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref(props.htmlVal);


const toolbarConfig: any = { excludeKeys: "fullScreen" };
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} };


// 更多详细配置看 https://www.wangeditor.com/v5/menu-config.html#%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87
editorConfig.MENU_CONF["uploadImage"] = {
  // 服务端上传地址，根据实际业务改写
  server: '',  // 上传地址
  meta: {
    ispic: '0'
  },
  headers: {
    token
  },
  debug: true,
  // form-data 的 fieldName，根据实际业务改写
  fieldName: "fileUpload",
  // 选择文件时的类型限制，根据实际业务改写
  allowedFileTypes: ["image/png", "image/jpg", "image/jpeg"],
  // 自定义插入图片
  // async customInsert(res: any, insertFn) {
  //   console.log(res, 'res')
  //   if (res.code) {
  //     setTimeout(() => {
  //       let img = getPicImg(res.data.result[0].uuid)
  //       insertFn(img);
  //     }, 1000);
  //   }
  // },

  // 根据后端返回使用的时候打开下面这个
  // customUpload(file, insertFn) {
  //   let formData = new FormData();
  //   formData.append("fileUpload", file);
  //   formData.append("ispic", '0');

  //   service({
  //     url: "/api/file/upload",
  //     method: 'post',
  //     data: formData,
  //     headers: {
  //       token
  //     }
  //   }).then(res => {
  //     console.log(res)
  //     if (res.data.code === '0000') {
  //       setTimeout(() => {
  //         // insertFn插入图片进编辑器
  //         let img = getPicImg(res.data.data.result[0].uuid)
  //         console.log(img)
  //         insertFn(img);
  //       }, 1000);
  //     }
  //   })
  // }


};

const handleCreated = editor => {
  // 记录 editor 实例，重要！
  editorRef.value = editor;
};


const handleChange = (editor: IDomEditor) => {
  emit('updatelVal', valueHtml.value)
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<template>
  <div class="wangeditor">
    <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" style="border-bottom: 1px solid #ccc" />
    <Editor v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode" style="height: 70vh; overflow-y: hidden"
      @onCreated="handleCreated" @onChange='handleChange' />
  </div>
</template>
